<template>
  <div class="goods_cate">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <el-button type="primary" plain @click="handleAdd">添加分类</el-button>

    <tree-grid
      class="mt-15"
      :treeStructure="true"
      :columns="columns"
      :data-source="dataSource"
      @deleteCate="deleteCategory"
      @editCate="editCategory"
    >
    </tree-grid>

    <!-- 分页组件 -->
    <el-pagination
      class="mt-15 page"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="1"
      :page-sizes="[10, 20, 30, 40]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>

    <!-- 添加分类 -->
    <el-dialog title="添加分类" :visible.sync="addDialogFormVisible" :before-close="closeDialog">
      <el-form :model="addForm" :rules="myrules" ref="addRef">
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="cat_name">
          <el-input v-model="addForm.cat_name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="父级名称" :label-width="formLabelWidth">
          <el-cascader
            change-on-select
            :options="cateList"
            v-model="selectedCates"
            :props="defaultProps"
            @change="handleChange">
          </el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible=false">取 消</el-button>
        <el-button type="primary" @click="confirmAdd">确 定</el-button>
      </div>
    </el-dialog>

        <!-- 编辑弹框 -->
    <el-dialog title="编辑用户" :visible.sync="editDialogFormVisible">
      <el-form :model="editForm" :rules="editrules" ref="editRef">
        <el-form-item label="分类名称" :label-width="formLabelWidth" prop="cat_name">
          <el-input v-model="editForm.cat_name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelselector('edit')">取 消</el-button>
        <el-button type="primary" @click="confirmEdit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCate, addCate, deleteCate, editCate } from '@/api'
import TreeGrid from '@/components/TreeGrid/TreeGrid'
export default {
  components: {
    TreeGrid
  },
  data () {
    return {
      cid: '',
      total: 0,
      pagenum: 1,
      pagesize: 10,
      dataSource: [],

      columns: [{
        text: '分类名称',
        dataIndex: 'cat_name',
        width: ''
      }, {
        text: '是否有效',
        dataIndex: 'cat_deleted',
        width: ''
      }, {
        text: '排序',
        dataIndex: 'cat_level',
        width: ''
      }],

      addDialogFormVisible: false,
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      formLabelWidth: '120px',
      myrules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      // 编辑分类:
      editDialogFormVisible: false,
      editrules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      editForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      cateList: [], // 级联选择器数据
      selectedCates: [], // 保存级联选择器选中之后的值
      defaultProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      }
    }
  },
  created () {
    this.initTable()
  },
  methods: {

    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.pagesize = val
      this.initTable()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.pagenum = val
      this.initTable()
    },
    // 添加分类
    handleAdd () {
      this.addDialogFormVisible = true
      getCate(2)
        .then(res => {
          this.cateList = res.data
        })
    },
    // 确认选择:
    handleChange (value) {
      if (value.length === 1) {
        this.addForm.cat_level = 1
        this.addForm.cat_pid = value[0]
      } else if (value.length === 2) {
        this.addForm.cat_level = 2
        this.addForm.cat_pid = value[1]
      }
    },
    // 确认添加:
    confirmAdd () {
      // 验证表单:
      this.$refs.addRef.validate(isPass => {
        if (isPass) {
          addCate(this.addForm)
            .then(res => {
              if (res.meta.status === 201) {
                // console.log(1)
                this.$message.success(res.meta.msg)
                this.addDialogFormVisible = false
                // 清空表单:
                this.addForm.cat_name = ''
                this.addForm.cat_pid = 0
                this.addForm.cat_level = 0
                // 清空级联选择器选中的节点id
                this.selectedCates = []
                this.initTable()
              } else {
                // console.log(2)
                this.$message.error(res.meta.msg)
              }
            })
        } else {
          this.$message.error('请输入正确的表单信息')
        }
      })
    },
    // 删除分类:
    deleteCategory (cid) {
      // console.log(cid)
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteCate(cid).then(res => {
            if (res.meta.status === 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.initTable()
            } else {
              this.$message.error(res.meta.meg)
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 编辑分类:
    editCategory (cid) {
      this.editDialogFormVisible = true
      this.cid = cid
    },
    // 确认编辑:
    confirmEdit () {
      this.$refs.editRef.validate(isPass => {
        if (isPass) {
          editCate(this.cid, this.editForm)
            .then(res => {
              if (res.meta.status === 200) {
                this.$message.success(res.meta.msg)
                this.editDialogFormVisible = false
                // 清空表单:
                this.editForm.cat_name = ''
                this.editForm.cat_pid = 0
                this.editForm.cat_level = 0
                this.initTable()
              } else {
                this.$message.error(res.meta.msg)
              }
            })
        } else {
          this.$message.error('请正确输入表单信息')
        }
      })
    },
    initTable () {
      getCate(3, this.pagesize, this.pagenum)
        .then(res => {
          this.total = res.data.total
          this.dataSource = res.data.result
        })
    },
    cancelselector (selector) {
      this[selector + 'DialogFormVisible'] = false
      this[selector + 'Form'] = {}
      this.$refs[selector + 'Ref'].clearValidate()
    },
    closeDialog (done) {
      this.addForm = {}
      this.$refs.addRef.clearValidate()
      done()
    }
  }

}
</script>

<style>

</style>
